﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Koala.Pro.Common;
using Koala.Pro.Core.Dto;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.Services;

namespace Koala.Pro.ViewModels
{
    public partial class RoleListViewModel : BaseListViewModel<RoleInfo, int, RolePagedDto>
    {
        [ObservableProperty]
        private TreeViewModel<RoleAndDeptTreeNode> roleTreeModel = new TreeViewModel<RoleAndDeptTreeNode>();

        public RoleListViewModel(IRoleService service)
            : base(service)
        {
            ExportFields = "ID,PID,HandNo,Name,Note,SortCode,Category,CompanyName,Creator,CreateTime,Deleted";
        }

        [RelayCommand]
        private async Task GetTree()
        {
            List<OuInfo> list = await SecurityHelper.GetMyTopGroup(App.ViewModel.UserInfo);
            List<RoleAndDeptTreeNode> treeeNodeList = new List<RoleAndDeptTreeNode>();
            foreach (OuInfo item in list)
            {
                if (item == null || item.IsDeleted)
                {
                    continue;
                }
                RoleAndDeptTreeNode topnode = new RoleAndDeptTreeNode(item);
                AddRole(item, topnode);
                if (item.Category == "集团")
                {
                    foreach (OuInfo item2 in await BLLFactory<IOuService>.Instance.GetAllCompany(item.Id))
                    {
                        RoleAndDeptTreeNode treeNode = new RoleAndDeptTreeNode(item2, topnode);
                        AddRole(item2, treeNode);
                    }
                }
                treeeNodeList.Add(topnode);
            }
            RoleTreeModel.TreeItems = treeeNodeList;
            RoleTreeModel.FilteredTreeItems = new List<RoleAndDeptTreeNode>(treeeNodeList);
        }

        private async void AddRole(OuInfo OuInfo, RoleAndDeptTreeNode treeNode)
        {
            foreach (RoleInfo item in await BLLFactory<IRoleService>.Instance.GetRolesByCompany(OuInfo.Id.ToString()))
            {
                RoleAndDeptTreeNode roleAndDeptTreeNode = new RoleAndDeptTreeNode();
                roleAndDeptTreeNode.Name = item.Name;
                roleAndDeptTreeNode.Tag = item.Id;
                roleAndDeptTreeNode.CompanyId = item.Company_ID;
                roleAndDeptTreeNode.RoleId = item.Id.ToString();
                treeNode.Children.Add(roleAndDeptTreeNode);
            }
        }
    }
}
